<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="nav-bar">
			<view class="nav-title">子账号管理</view>
			<view class="nav-btn" @tap="addSubaccount">添加子账号</view>
		</view>

		<!-- 搜索框 -->
		<view class="search-box">
			<view class="search-input">
				<text class="iconfont icon-search"></text>
				<input type="text" v-model="searchKey" placeholder="搜索子账号" confirm-type="search"
					@input="handleSearch" />
			</view>
		</view>

		<!-- 状态统计 -->
		<view class="stats">
			<view class="stat-item">
				<text class="stat-value">{{ totalAccounts }}</text>
				<text class="stat-label">总账号数</text>
			</view>
			<view class="stat-item">
				<text class="stat-value active">{{ activeAccounts }}</text>
				<text class="stat-label">已启用</text>
			</view>
			<view class="stat-item">
				<text class="stat-value inactive">{{ inactiveAccounts }}</text>
				<text class="stat-label">已停用</text>
			</view>
		</view>

		<!-- 无数据提示 -->
		<view class="empty-tip" v-if="subaccounts.length === 0 && !loading">
			<image class="empty-image" src="/static/images/empty.png"></image>
			<text class="empty-text">暂无子账号，请点击右上角"添加子账号"按钮添加</text>
		</view>

		<view v-if="loading" class="loading">
			<text>加载中...</text>
		</view>

		<!-- 子账号列表 -->
		<view class="subaccount-list" v-else-if="subaccounts.length > 0">
			<view class="subaccount-item" v-for="(item, index) in filteredList" :key="index" @tap="viewDetail(item)">
				<view class="item-left">
					<view class="avatar" :style="{backgroundColor: getRandomColor(item.name)}">
						{{ item.name.substring(0, 1) }}
					</view>
					<view class="info">
						<view class="name">{{ item.name }}</view>
						<view class="username">@{{ item.username }}</view>
					</view>
				</view>
				<view class="item-right">
					<view :class="['status', item.status === 1 ? 'status-active' : 'status-inactive']">
						{{ item.status === 1 ? '已启用' : '已停用' }}
					</view>
					<view class="action">
						<text class="iconfont icon-right"></text>
					</view>
				</view>
			</view>
		</view>

		<!-- 添加子账号弹窗 -->
		<uni-popup ref="popup" type="bottom" :mask-click="false">
			<view class="popup-content">
				<view class="popup-title">{{ isEdit ? '编辑子账号' : '添加子账号' }}</view>
				<!-- 添加时显示用户名和密码字段 -->
				<template v-if="!isEdit">
					<view class="form-item">
						<text class="label">用户名</text>
						<input type="text" v-model="form.username" placeholder="请输入用户名" :disabled="isEdit" />
					</view>
					<view class="form-item">
						<text class="label">密码</text>
						<input type="password" v-model="form.password" placeholder="请输入密码" :disabled="isEdit" />
					</view>
				</template>
				<view class="form-item">
					<text class="label">姓名</text>
					<input type="text" v-model="form.name" placeholder="请输入姓名" />
				</view>
				<view class="form-item">
					<text class="label">手机号</text>
					<input type="number" v-model="form.phone" placeholder="请输入手机号" maxlength="11" />
				</view>
				<view class="form-item">
					<text class="label">状态</text>
					<switch color="#FFD100" :checked="form.status === 1" @change="statusChange" />
				</view>
				<view class="btn-group">
					<button class="btn btn-cancel" @tap="closePopup">取消</button>
					<button class="btn btn-confirm" @tap="saveSubaccount" :disabled="saving">
						{{ saving ? '处理中...' : '确认' }}
					</button>
				</view>
			</view>
		</uni-popup>

		<!-- 详情弹窗 -->
		<uni-popup ref="detailPopup" type="bottom" :mask-click="false">
			<view class="popup-content">
				<view class="popup-title">子账号详情</view>
				<view class="detail-item">
					<text class="detail-label">姓名</text>
					<text class="detail-value">{{ currentSubaccount.name }}</text>
				</view>
				<view class="detail-item">
					<text class="detail-label">账号名</text>
					<text class="detail-value">{{ currentSubaccount.username }}</text>
				</view>
				<view class="detail-item">
					<text class="detail-label">手机号</text>
					<text class="detail-value">{{ currentSubaccount.phone }}</text>
				</view>
				<view class="detail-item">
					<text class="detail-label">状态</text>
					<text :class="['detail-value', currentSubaccount.status === 1 ? 'text-active' : 'text-inactive']">
						{{ currentSubaccount.status === 1 ? '已启用' : '已停用' }}
					</text>
				</view>
				<view class="detail-item">
					<text class="detail-label">创建时间</text>
					<text class="detail-value">{{ formatDate(currentSubaccount.create_time) }}</text>
				</view>
				<view class="btn-group">
					<button class="btn btn-edit" @tap="editSubaccount">编辑</button>
					<button class="btn btn-delete" @tap="deleteSubaccount">删除</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		getList,
		addAccount,
		updateAccount,
		deleteAccount
	} from '@/api/account.js'

	export default {
		data() {
			return {
				searchKey: '',
				subaccounts: [],
				form: {
					id: '',
					username: '',
					password: '',
					name: '',
					phone: '',
					role: 1,
					status: 1,
					createTime: null
				},
				isEdit: false,
				currentSubaccount: {},
				loading: false,
				saving: false
			};
		},
		computed: {
			filteredList() {
				if (!this.searchKey) return this.subaccounts;
				const keyword = this.searchKey.toLowerCase();
				return this.subaccounts.filter(acc =>
					acc.name.toLowerCase().includes(keyword) ||
					(acc.username && acc.username.toLowerCase().includes(keyword)) ||
					(acc.phone && acc.phone.includes(keyword))
				);
			},
			totalAccounts() {
				return this.subaccounts.length;
			},
			activeAccounts() {
				return this.subaccounts.filter(acc => acc.status === 1).length;
			},
			inactiveAccounts() {
				return this.subaccounts.filter(acc => acc.status === 0).length;
			}
		},
		onLoad() {
			this.getSubaccounts();
		},
		methods: {
			// 获取子账号列表
			async getSubaccounts() {
				try {
					this.loading = true;
					const res = await getList();
					if (res && res.data) {
						this.subaccounts = res.data;
					}
				} catch (e) {
					console.error("获取子账号列表失败:", e);
					uni.showToast({
						title: '获取账号列表失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			// 搜索处理
			handleSearch() {
				// 搜索逻辑已通过computed属性filteredList实现
			},

			// 查看详情
			viewDetail(account) {
				this.currentSubaccount = {
					...account
				};
				this.$refs.detailPopup.open();
			},

			// 编辑子账号
			editSubaccount() {
				this.isEdit = true;
				this.form = {
					...this.currentSubaccount
				};
				this.$refs.detailPopup.close();
				setTimeout(() => {
					this.$refs.popup.open();
				}, 300);
			},

			// 添加子账号
			addSubaccount() {
				this.isEdit = false;
				this.form = {
					id: '',
					username: '',
					password: '',
					name: '',
					phone: '',
					role: 1,
					status: 1,
					createTime: null
				};
				this.$refs.popup.open();
			},

			// 删除子账号
			async deleteSubaccount() {
				uni.showModal({
					title: '提示',
					content: '确定要删除该子账号吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								const id = this.currentSubaccount.subaccount_id;
								await deleteAccount(id);

								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});

								// 关闭详情弹窗并刷新列表
								this.$refs.detailPopup.close();
								this.getSubaccounts();
							} catch (e) {
								console.error("删除失败:", e);
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},

			// 状态切换
			statusChange(e) {
				this.form.status = e.detail.value ? 1 : 0;
			},

			// 保存子账号
			async saveSubaccount() {
				// 表单验证
				if (!this.isEdit) {
					// 添加时验证用户名和密码
					if (!this.form.username.trim()) {
						uni.showToast({
							title: '请输入用户名',
							icon: 'none'
						});
						return;
					}
					if (!this.form.password) {
						uni.showToast({
							title: '请输入密码',
							icon: 'none'
						});
						return;
					}
					if (this.form.password.length < 6) {
						uni.showToast({
							title: '密码至少需要6位',
							icon: 'none'
						});
						return;
					}
				}

				if (!this.form.name.trim()) {
					uni.showToast({
						title: '请输入姓名',
						icon: 'none'
					});
					return;
				}
				if (!/^1[3-9]\d{9}$/.test(this.form.phone)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return;
				}

				try {
					this.saving = true;
					if (this.isEdit) {
						// 编辑
						const updateData = {
							subaccount_id: this.form.subaccount_id,
							name: this.form.name,
							phone: this.form.phone,
							status: this.form.status
						};
						await updateAccount(updateData);
					} else {
						// 新增
						const addData = {
							username: this.form.username,
							password: this.form.password,
							name: this.form.name,
							phone: this.form.phone,
							role: this.form.role,
							status: this.form.status
						};
						await addAccount(addData);
					}

					uni.showToast({
						title: this.isEdit ? '编辑成功' : '添加成功',
						icon: 'success'
					});

					// 关闭弹窗并刷新列表
					this.$refs.popup.close();
					this.getSubaccounts();
				} catch (e) {
					console.error("保存失败:", e);
					const errorMsg = e.message || (this.isEdit ? '编辑失败' : '添加失败');
					uni.showToast({
						title: errorMsg,
						icon: 'none'
					});
				} finally {
					this.saving = false;
				}
			},

			closePopup() {
				this.$refs.popup.close();
			},

			// 格式化日期
			formatDate(timestamp) {
				if (!timestamp) return '';
				const date = new Date(timestamp);
				return `${date.getFullYear()}-${String(date.getMonth()+1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
			},

			// 获取随机颜色 (美团黄色系)
			getRandomColor(str) {
				const colors = [
					'#FFD100', // 美团黄
					'#FFC300',
					'#FFB700',
					'#FFA900',
					'#FF9D00'
				];
				if (!str) return colors[0];
				const code = str.split('')
					.reduce((sum, char) => sum + char.charCodeAt(0), 0);
				return colors[code % colors.length];
			}
		}
	};
</script>

<style>
	.container {
		background-color: #F5F5F5;
		min-height: 100vh;
	}

	/* 导航栏 */
	.nav-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 30rpx;
		height: 90rpx;
		background-color: #FFFFFF;
		border-bottom: 1rpx solid #EEEEEE;
	}

	.nav-title {
		font-size: 34rpx;
		font-weight: bold;
		color: #333333;
	}

	.nav-btn {
		font-size: 28rpx;
		color: #FFD100;
	}

	/* 搜索框 */
	.search-box {
		padding: 20rpx 30rpx;
		background-color: #FFFFFF;
	}

	.search-input {
		display: flex;
		align-items: center;
		height: 70rpx;
		background-color: #F5F5F5;
		border-radius: 35rpx;
		padding: 0 30rpx;
	}

	.icon-search {
		font-size: 28rpx;
		color: #999999;
		margin-right: 10rpx;
	}

	/* 统计区域 */
	.stats {
		display: flex;
		justify-content: space-around;
		background-color: #FFFFFF;
		padding: 20rpx 0;
		margin: 20rpx 0;
		border-radius: 16rpx;
	}

	.stat-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.stat-value {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}

	.stat-value.active {
		color: #07C160;
	}

	.stat-value.inactive {
		color: #F56C6C;
	}

	.stat-label {
		font-size: 24rpx;
		color: #999;
	}

	/* 空数据提示 */
	.empty-tip {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 30rpx;
		background-color: #FFFFFF;
		border-radius: 16rpx;
		margin-top: 20rpx;
	}

	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
	}

	.empty-text {
		font-size: 28rpx;
		color: #999999;
		text-align: center;
		line-height: 1.5;
	}

	.loading {
		text-align: center;
		padding: 40rpx;
		color: #999;
		font-size: 28rpx;
	}

	/* 子账号列表 */
	.subaccount-list {
		padding: 20rpx 0;
		background-color: #FFFFFF;
		margin-top: 20rpx;
		border-radius: 16rpx;
	}

	.subaccount-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #EEEEEE;
	}

	.subaccount-item:last-child {
		border-bottom: none;
	}

	.item-left {
		display: flex;
		align-items: center;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background-color: #FFD100;
		color: #FFFFFF;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 32rpx;
		font-weight: bold;
		margin-right: 20rpx;
	}

	.info {
		display: flex;
		flex-direction: column;
	}

	.name {
		font-size: 30rpx;
		color: #333333;
		margin-bottom: 8rpx;
	}

	.username {
		font-size: 24rpx;
		color: #999999;
	}

	.item-right {
		display: flex;
		align-items: center;
	}

	.status {
		font-size: 24rpx;
		padding: 4rpx 12rpx;
		border-radius: 30rpx;
		margin-right: 20rpx;
	}

	.status-active {
		background-color: #E8F5E9;
		color: #07C160;
	}

	.status-inactive {
		background-color: #FFEBEE;
		color: #F44336;
	}

	.action {
		font-size: 28rpx;
		color: #CCCCCC;
	}

	/* 弹窗样式 */
	.popup-content {
		background-color: #FFFFFF;
		border-radius: 24rpx 24rpx 0 0;
		padding: 30rpx;
	}

	.popup-title {
		font-size: 34rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 30rpx;
		text-align: center;
	}

	.form-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #EEEEEE;
	}

	.label {
		font-size: 28rpx;
		color: #333333;
		width: 150rpx;
	}

	input,
	.picker {
		flex: 1;
		font-size: 28rpx;
		color: #333333;
		text-align: right;
		padding: 12rpx 0;
	}

	.btn-group {
		display: flex;
		justify-content: space-between;
		margin-top: 50rpx;
	}

	.btn {
		width: 48%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border-radius: 40rpx;
		font-size: 30rpx;
	}

	.btn:disabled {
		opacity: 0.6;
	}

	.btn-cancel {
		background-color: #F5F5F5;
		color: #666666;
	}

	.btn-confirm {
		background-color: #FFD100;
		color: #333333;
	}

	.btn-edit {
		background-color: #FFD100;
		color: #333333;
	}

	.btn-delete {
		background-color: #F44336;
		color: #FFFFFF;
	}

	/* 详情弹窗 */
	.detail-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #EEEEEE;
	}

	.detail-label {
		font-size: 28rpx;
		color: #666666;
	}

	.detail-value {
		font-size: 28rpx;
		color: #333333;
	}

	.text-active {
		color: #07C160;
	}

	.text-inactive {
		color: #F44336;
	}
</style>